<template>
  <div class="users-container">
    <!-- 头部导航 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb> -->
    <bread :params1="'用户管理'" :params2="'用户列表'"></bread>

    <el-card class="box-card">
      <div>
        <el-input
          placeholder="请输入内容"
          v-model="users.query"
          style="width: 30%"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="usersapi()"
          ></el-button
        ></el-input>
        <el-button type="primary" style="margin-left: 30px" @click="usersAddBtn"
          >添加用户</el-button
        >
      </div>
      <!-- 显示的数据 -->
      <el-table
        :data="userList"
        border
        style="width: 100%"
        highlight-current-row
      >
        <!-- prop对应列内容的字段名，也可以使用 property 属性 -->
        <el-table-column type="index" label="#" width="180"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- <pre>{{ scope.row }}</pre> -->
            <el-switch
              @change="switchbtn(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="editbtn(scope.row)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>

            <el-button
              @click="delbtn(scope.row)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>

            <el-tooltip content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="addRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>

          <!-- 确认删除弹框 -->
          <template>
            <el-button type="text" @click="delbtn"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="Number(users.pagenum)"
          :page-sizes="[10, 15, 20]"
          :page-size="users.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 编辑用户信息弹框 -->
    <template>
      <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rulesEdit" ref="form">
          <el-form-item
            prop="username"
            label="用户名"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="disable"
              v-model="form.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="disp"
            prop="password"
            label="密码"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            prop="mobile"
            label="手机"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-if="!disp" type="primary" @click="closeDialog"
            >修改</el-button
          >
          <el-button v-if="disp" type="primary" @click="closeDialog2"
            >添加</el-button
          >
        </div>
      </el-dialog>
    </template>

    <!-- 分配角色的信息弹窗 -->
    <template>
      <el-dialog title="分配角色" :visible.sync="dialogFormVisibleRoles">
        <el-form :model="form">
          <el-form-item label="当前用户：" :label-width="formLabelWidth">
            <p>{{ username }}</p>
          </el-form-item>
          <el-form-item label="当前角色：" :label-width="formLabelWidth">
            <p>{{ role_name }}</p>
          </el-form-item>
          <el-form-item label="分配新角色:" :label-width="formLabelWidth">
            <el-select v-model="form.region" placeholder="请选择">
              <el-option
                v-for="(item, index) in roleslist"
                :label="item.roleName"
                :value="item.id"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleRoles = false">取 消</el-button>
          <el-button type="primary" @click="rolesBtn">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </div>
</template>
<script>
import {
  users_api,
  usersState_api,
  usersDel_api,
  usersEdit_api,
  usersAdd_api,
  roles_api,
  addUserRole_api
} from "@/api";
import { returnMessage } from "@/common/$message.js";

export default {
  data() {
    return {
      //  定义参数
      users: {
        query: "",
        pagesize: 10,
        pagenum: 1
      },
      userList: [],
      total: 1,
      // 编辑用户的对话框   dialogFormVisible为true就显示对话框
      dialogFormVisible: false,
      //密码框显示或隐藏  true显示  false不显示
      disp: false,
      //用户名框禁用或不禁用  true禁用  false不禁用
      disable: false,
      form: {
        id: "",
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      rulesEdit: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 11, message: "长度在 3 到11 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 3, max: 11, message: "长度在 3 到 11 个字符", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "长度在 11个字符", trigger: "blur" }
        ]
      },
      formLabelWidth: "120px",
      //分配角色  数据
      //按钮弹窗
      dialogFormVisibleRoles: false,
      id: "",
      username: "",
      role_name: "",
      rid: "",
      roleslist: [],
      props: {
        label: "roleName"
      }
    };
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.users.pagesize = val;
      this.usersapi();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.users.pagenum = val;
      this.usersapi();
    },
    //发送 users_api请求数据的方法
    async usersapi() {
      const { data: res } = await users_api(this.users);
      // console.log(res.data, 222222222);
      this.userList = res.data.users;
      //获取数据里的总页数
      this.total = res.data.total;
    },
    // 开关按钮
    async switchbtn(rows) {
      // console.log(rows, 4444444);
      // usersState_api   rows.mg_state
      const { data: res } = await usersState_api({
        uId: rows.id,
        type: rows.mg_state
      });
      console.log(res, 666666);
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    //删除单个用户按钮
    delbtn(rows) {
      // console.log(rows, 55555555555);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
          const { data: res } = await usersDel_api(rows.id);
          // console.log(res, 999999999);
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
          } else {
            this.$message.error(res.meta.msg);
          }
          this.usersapi();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // const { data: res } = await usersDel_api(rows.id);
    // // console.log(res, 999999999);
    // if (res.meta.status == 200) {
    //   this.$message.success(res.meta.msg);
    // } else {
    //   this.$message.error(res.meta.msg);
    // }
    // this.usersapi();

    //编辑用户信息
    editbtn(rows) {
      //密码框隐藏 默认就是false  这里要赋值  下面的要不要都可以  你赋值不对
      this.disp = false;
      //点击编辑按钮  获取当前行rows的用户信息 并将当前行的用户信息的值 赋值给 对话框的每一项 点击对话框的确认按钮 进行二次校验  发送请求
      // console.log(rows, 7777777777);
      this.dialogFormVisible = true;

      // 用户名框禁用 true
      this.disable = true;
      this.form.username = rows.username;
      this.form.email = rows.email;
      this.form.mobile = rows.mobile;
      this.form.id = rows.id;
    },
    //编辑用户信息  二次校验
    closeDialog() {
      // console.log(this.$refs.form.validate, 8888888);
      this.$refs.form.validate(async valid => {
        // console.log(valid, 000000);
        if (valid) {
          // alert("submit!");
          // 如果为true表示二次验证成功 可以发送请求
          // console.log(this.form, 111111);
          const { data: res } = await usersEdit_api(this.form);
          console.log(res, 888888);

          if (res.meta.status == 200) {
            //编辑信息成功后手动关闭对话框  并显示成功后的提示信息
            this.dialogFormVisible = false;
            this.$message.success(res.meta.msg);
          } else {
            this.$message.error(res.meta.msg);
          }
          //重新渲染用户信息  调用获取用户信息的函数
          this.usersapi();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加用户
    usersAddBtn() {
      //密码框隐藏 默认是false
      this.disp = true;
      //显示模板输入框
      this.dialogFormVisible = true;
      //用户名框不禁用
      this.disable = false;
      //表单清空
      // this.from = {
      //   id: "",
      //   username: "",
      //   password: "",
      //   email: "",
      //   mobile: ""
      // };
      this.form.username = "";
      this.form.password = "";
      this.form.email = "";
      this.form.mobile = "";
      this.form.id = "";
    },
    //添加用户信息  二次校验
    closeDialog2() {
      // console.log(this.$refs.form.validate, 8888888);
      this.$refs.form.validate(async valid => {
        if (valid) {
          // alert("submit!");
          // 如果为true表示二次验证成功 可以发送请求
          // console.log(this.form, 111111);
          const { data: res } = await usersAdd_api(this.form);
          console.log(res, 888888);

          if (res.meta.status == 201) {
            //添加用户成功后手动关闭对话框  并显示成功后的提示信息
            this.dialogFormVisible = false;
            this.$message.success(res.meta.msg);
          } else {
            this.$message.error(res.meta.msg);
          }
          this.usersapi();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //分配角色
    addRoles(rows) {
      this.dialogFormVisibleRoles = true;
      // console.log(rows, 7777777777);
      this.id = rows.id; //  获取用户id
      this.username = rows.username;
      this.role_name = rows.role_name;
      //在created()  中发送获取角色列表的api
    },
    // 发送获取角色列表的api
    async rolesapi() {
      const { data: res } = await roles_api();
      console.log(res.data, 123213123);
      this.roleslist = res.data;
    },
    //分配角色对话框中的确认按钮
    async rolesBtn() {
      const { data: res } = await addUserRole_api({
        id: this.id,
        rid: this.rid
      });
      //调用 判断发送请求后的函数
      const data = returnMessage(res, this.$message);
      console.log(res, 22222);
      this.dialogFormVisibleRoles = false;
    }
  },
  created() {
    this.usersapi();
    //调用获取角色列表的api
    this.rolesapi();
  }
};
</script>
<style scoped lang="less">
.users-container {
  .box-card {
    margin-top: 16px;
  }
  .el-table {
    margin: 15px 0;
  }
}
</style>
